package com.comac.print.component.app.mqListener;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventBusI;
import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.Message;
import com.comac.mom.simpleintegration.mq.BaseMessageListener;
import com.comac.mom.simpleintegration.mq.config.MqConfig;
import com.comac.print.component.app.common.PrintCommon;
import com.comac.print.component.app.domainevent.PrintRecordEvent;
import com.comac.print.component.app.handler.MQLogHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description 打印组件监听器
 * @Author YE
 * @Date 2022/4/19 10:16
 */
@Component("PRINT-COMPONENT-APPLY")
@Slf4j
public class PrintMessageListener extends BaseMessageListener {

    @Autowired
    private EventBusI eventBus;

    @Autowired
    private MqConfig mqConfig;

    @Autowired
    private MQLogHandler mqLogHandler;

    @Override
    public Action consume(Message message) {
        PrintCommon printCommon = null;
        PrintRecordEvent printRecordEvent = null;
        Response response = null;
        try {
            printCommon = super.deserialize(message, PrintCommon.class);
            printRecordEvent = new PrintRecordEvent();
            printRecordEvent.setPrintCommon(printCommon);
            log.info("printRecordEvent event param is {}", JSON.toJSONString(printRecordEvent));
            response = eventBus.fire(printRecordEvent);
            log.info("printRecordEvent event result is {}", JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("print task error!", e);
            // 如果超过重试次数，日志落地数据库
            if(super.retryCount(message) >= mqConfig.getMaxReconsumeNum()) {
                mqLogHandler.addMqLog(message, printRecordEvent, response, e);
                return Action.CommitMessage;
            }
            return Action.ReconsumeLater;
        }
        mqLogHandler.addMqLog(message, printRecordEvent, response);
        return Action.CommitMessage;
    }

}
